import matplotlib.pyplot as plt
from utils import uniform_samples
import numpy as np

def plot_result(intervals, y_true, fitting_results, x_experiment, x_samples, y_samples_noisy, num_experiments=1000):
    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))
    axes = axes.flatten()
    
    # 绘制真实的函数曲线
    for ax in axes:
        ax.plot(x_experiment, y_true, label="True Function", color="black")

    # 遍历各个插值结果，并仅绘制对应区间的结果
    for idx, (interval, results) in enumerate(fitting_results.items()):
        x_experiment = np.array(x_experiment)
        interval_length = (x_experiment.max() - x_experiment.min()) / interval
        
        for i in range(interval):
            start = x_experiment.min() + i * interval_length
            end = start + interval_length

            x_piecewise = uniform_samples(start, end, num_experiments)
        
            for result in results[i * 4: i * 4 + 4]:
                degree = result['degree']
                y_fit = result['y_fit']
                
                if isinstance(y_fit, (list, np.ndarray)) and len(y_fit) == len(x_piecewise):
                    axes[degree - 1].plot(x_piecewise, y_fit, label=f"Interval {i+1} Degree {degree} Fit", linestyle="--")
                else:
                    print(f"Unexpected data format for y_fit: {type(y_fit)} or mismatched length")

    # 绘制样本点
    for ax in axes:
        ax.scatter(x_samples, y_samples_noisy, label="Samples", color="red", zorder=5)
        ax.legend()
        ax.set_title("Piecewise Curve Fitting Results")
        ax.set_xlabel("x")
        ax.set_ylabel("y")
        ax.grid(True)

    plt.tight_layout()
    plt.show()